/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.service.WxPayService;
import com.yami.shop.bean.app.param.JiaoyouOrderPayParam;
import com.yami.shop.bean.app.param.RechargePackageParam;
import com.yami.shop.bean.model.JiaoyouOrder;
import com.yami.shop.bean.model.RechargePackage;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.JiaoyouOrderMapper;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.JiaoyouOrderService;
import com.yami.shop.service.RechargePackageService;
import com.yami.shop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author lgh on 2018/10/26.
 */
@RestController
@RequestMapping
@Api(tags = "支付接口")
@Slf4j
public class PayController {

    @Autowired
    private UserService userService;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private JiaoyouOrderService jiaoyouOrderService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private JiaoyouOrderMapper jiaoyouOrderMapper;


    @PostMapping("/p/pay")
    @ApiOperation(value = "支付", notes = "支付")
    public ResponseEntity<Object> pay(@RequestBody JiaoyouOrderPayParam param, HttpServletRequest httpServletRequest) {
        JiaoyouOrder order = jiaoyouOrderService.getByOrderNum(param.getOrderNumber());
        Assert.notNull(order, "请提交有效订单编号进行支付");
        if(param.getPayType() == 1){
            try {
                WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
                orderRequest.setBody("小慧同学-" + order.getProdName());
                orderRequest.setOutTradeNo(order.getOrderNumber());
                orderRequest.setTotalFee(order.getActualTotal().multiply(BigDecimal.valueOf(100)).intValue());//元转成分
                orderRequest.setSpbillCreateIp(httpServletRequest.getRemoteAddr());
                orderRequest.setTimeStart(DateUtil.format(order.getCreateTime(), "yyyyMMddHHmmss"));
                orderRequest.setTimeExpire(DateUtil.format(DateUtil.offsetMinute(order.getCreateTime(), 10), "yyyyMMddHHmmss"));
                orderRequest.setNotifyUrl("https://xiuqiu.xiuqiu.cc/api/app/wx");
                return ResponseEntity.ok(wxPayService.createOrder(orderRequest));
            } catch (Exception e) {
                log.error("微信支付失败！订单号：{},原因:{}", order.getOrderNumber(), e.getMessage());
                e.printStackTrace();
                return ResponseEntity.badRequest().body("订单支付失败，请重试");
            }
        }else{
            return ResponseEntity.badRequest().body("暂不支持非微信支付");
        }

    }

    @ResponseBody
    @RequestMapping("/wx")
    public String payNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);
            if (result.getResultCode().equals("SUCCESS")) {
                // 加入自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
                String orderId = result.getOutTradeNo();
                JiaoyouOrder order = jiaoyouOrderService.getByOrderNum(orderId);
                String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());
                if (order.getIsPayed() != 1) {
                    jiaoyouOrderService.update(Wrappers.lambdaUpdate(new JiaoyouOrder())
                            .eq(JiaoyouOrder::getOrderNumber, orderId).setSql("is_payed=1,status=2"));

                    if(order.getOrderType()==1){
                        jiaoyouOrderService.doRecharge(order);
                    }else if (order.getOrderType() == 2){
                        jiaoyouOrderService.doVipPay(order);
                    }
                }
            }
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }

        return WxPayNotifyResponse.success("处理成功!");
    }

    @GetMapping("/payOrder")
    @ApiOperation(value = "查询支付状态",notes = "查询支付状态")
    public ResponseEntity<IPage<JiaoyouOrder>> getPayOrder(PageParam<JiaoyouOrder> page){
    String userId = SecurityUtils.getUser().getUserId();
    QueryWrapper<JiaoyouOrder> wrapper = new QueryWrapper<JiaoyouOrder>();
    wrapper.eq("user_id",userId);
    IPage<JiaoyouOrder> queryOrder = jiaoyouOrderMapper.selectPage(page,wrapper);
    return ResponseEntity.ok(queryOrder);
}


}
